<?php

namespace app\user\controller;

use app\common\controller\Api;
use app\common\library\Email;
use app\common\library\Sms as Smslib;
use app\common\model\Store as StoreModel;
use app\common\model\Order as OrderModel;
use app\common\model\StoreProject;
use think\Db;
use think\Exception;
use think\Request;

/**
 * 订单提交接口
 */
class Order extends Api
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    //时间段
    public function time()
    {
        $start_time = \app\common\model\Config::get(['name'=>'start_time'])->value;
        $end_time = \app\common\model\Config::get(['name'=>'end_time'])->value;
        // 开始时间和结束时间（一天的时间范围）
        $startTime = strtotime('00:00');
        $endTime = strtotime('23:59');

        // 用于存储时间段的数组
        $timeSlots = [];

        // 循环生成时间段，每次增加15分钟
        for ($time = $startTime; $time <= $endTime; $time += 15 * 60) {

            if (date('H:i:s', $time)>=$start_time&&date('H:i:s', $time)<=$end_time){
                $is_sign = 1;
            } else {
                $is_sign = 0;
            }
            $timeSlots[] = [
                'time'=>date('H:i', $time),
                'is_sign'=>$is_sign
            ];
        }

        $this->success('请求成功',$timeSlots);
    }

    /**
     * 提交
     *
     */
    public function add()
    {

        $order_model = new OrderModel();

        $data = [
            'store_id'=>input('store_id',0),
            'project_id'=>input('project_id',0),
            'date'=>input('date',''),
            'num'=>input('num',1),
            'last_name'=>input('last_name',''),
            'first_name'=>input('first_name',''),
            'phone'=>input('phone',''),
            'email'=>input('email',''),
            'remark'=>input('remark',''),
            'order_no'=>$order_model->order_no(),
            'order_status_name'=>'未开始',
        ];
        $data['date_timestamp'] = strtotime($data['date']);
        if (empty($data['store_id'])){
            $this->error('REQUEST_STORE_ID');
        }
        //dump($data);die;
        if (empty($data['project_id'])){
            $this->error('REQUEST_PROJECT_ID');
        }
        if (empty($data['date'])){
            $this->error('Please enter Date');
        }
        if (empty($data['last_name'])){
            $this->error('Please enter Last Name');
        }
        if (empty($data['first_name'])){
            $this->error('Please enter First Name');
        }
        if (empty($data['phone'])){
            $this->error('Please enter Phone');
        }
        if (empty($data['email'])){
            $this->error('Please enter Email');
        }
        $startOfDay = strtotime($data['date'])-3600;
        $endOfDay = strtotime($data['date'])+3600;
        $store = StoreModel::get($data['store_id']);

        $max_time_subscribe = $store['max_time_subscribe'];
        $not_allow_subscribe_time = $store['not_allow_subscribe_time'];

        if ($not_allow_subscribe_time>0){
            if (strtotime($data['date'])-time()<$not_allow_subscribe_time*3600){
                $this->error($not_allow_subscribe_time.'小时内不允许预约');
            }
        }

        $order_count = OrderModel::where(['store_id'=>$data['store_id']])
            ->whereTime('date', 'between', [date('Y-m-d H::i:s',$startOfDay), date('Y-m-d H::i:s',$endOfDay)])
            ->count();

        if ($max_time_subscribe>0){
            if ($max_time_subscribe<$order_count){
                $this->error('当前时间已预约满');
            }
        }
        Db::startTrans();
        try {
            $res = $order_model->save($data);
            if ($res){
                $store = \app\admin\model\Store::get($data['store_id']);
                $project = StoreProject::get($data['project_id']);
                $message_title = \app\common\model\Config::get(['name'=>'submit_title'])->value;
                $request = Request::instance();
                $domain=$request->domain();
                $url = $domain.'/dist/#/complete?order_id='.$order_model->order_id;
                //$message_content = \app\common\model\Config::get(['name'=>'submit_content'])->value;
                //$message_title = '订单编号:'.$info['order_no'].'技师'.$this->auth->nickname.'已上钟';
                //$message_content = '订单编号:'.$info['order_no'].'技师'.$this->auth->nickname.'已上钟';
            //发送短信
                $ret = Smslib::send($data['phone'], null, 'add',$store['store_name'],$project['project_name'],$data['date'],$store['address']);
                if (!$ret) {
                    Db::rollback();
                    throw new Exception('发送失败，请检查短信配置是否正确');
                }

        $content = '<!DOCTYPE html>
                <html lang="en">
                <head>
                   <meta charset="UTF-8">
                   <meta name="viewport" content="width=device-width, initial-scale=1.0">
                   <title>Appointment Confirmation</title>
                </head>
                <body style="margin: 0; padding: 0;">
                   <table width="100%" cellspacing="0" cellpadding="0">
                      <tr>
                         <td align="center" valign="top" style="padding: 10px;">
                            <table width="100%" max-width="600" cellspacing="0" cellpadding="0">
                               <tr>
                                  <td align="center" style="font-size: 20px; margin-bottom: 30px; padding: 10px 0;">Appointment Scheduled</td>
                               </tr>
                               <tr>
                                  <td style="box-shadow: 0 0 8px 0 #0000001a; padding: 18px 14px; box-sizing: border-box;">
                                     <table width="100%" cellspacing="0" cellpadding="0">
                                        <tr>
                                           <td width="52px" style="color: #7F7F7F; padding-right: 4px;">What</td>
                                           <td>'.$project['project_name'].'</td>
                                        </tr>
                                        <tr>
                                           <td height="16"></td>
                                        </tr>
                                        <tr>
                                           <td width="52px" style="color: #7F7F7F; padding-right: 4px;">When</td>
                                           <td>'.$data['date'].'</td>
                                        </tr>
                                        <tr>
                                           <td height="16"></td>
                                        </tr>
                                        <tr>
                                           <td width="52px" style="color: #7F7F7F; padding-right: 4px;">Where</td>
                                           <td style="word-break: break-word;">'.$store['address'].'</td>
                                        </tr>
                                        <tr>
                                           <td height="20" colspan="2"></td>
                                        </tr>
                                        <tr>
                                           <td colspan="2" align="center" style="color: #A1A1A1; font-size: 14px; text-align: center; padding: 0 5%;">Thank you, your appointment has been successfully scheduled.</td>
                                        </tr>
                                     </table>
                                  </td>
                               </tr>
                   
                               <tr>
                                  <td align="center" valign="middle" style="padding: 30px 0 10px; text-align: center;">
                                     <!--[if mso]>
                                                      <table align="center" border="0" cellspacing="0" cellpadding="0">
                                                      <tr><td>
                                                      <![endif]-->
                                     <a href="'.$url.'"
                                        style="display: block; width: 227px; height: 54px; opacity: 1; background: #030302; color: #fff; line-height: 54px; text-align: center; font-size: 12px; text-decoration: none; margin: 0 auto;">Change/Cancel
                                        Appointment</a>
                                     <!--[if mso]>
                                                      </td></tr>
                                                      </table>
                                                      <![endif]-->
                                  </td>
                               </tr>
                            </table>
                         </td>
                      </tr>
                   </table>
                </body>
                </html>';
                $email = new Email;
                $result = $email
                    ->to($data['email'])
                    ->subject($message_title)
                    ->message($content)
                    ->send();

                if (!$result) {
                    Db::rollback();
                    throw new Exception('邮箱发送失败');
                }
                Db::commit();
            } else {
                Db::rollback();
                throw new Exception('error');
            }
        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('success',$order_model->order_id);

    }

    //订单详情
    public function info()
    {
        $order_id = input('order_id',0);

        $info = OrderModel::get($order_id);
        if (!$info)$this->error('订单不存在');
        $order_model = new OrderModel();

        $res = $order_model->info($order_id);

        $this->success('',$res);
    }

    //修改订单
    public function modify()
    {
        $order_id = input('order_id',0);
        $date = input('date','');
        $info = OrderModel::get($order_id);
        $store = StoreModel::get($info['store_id']);
        $not_allow_cancel_time = $store['not_allow_cancel_time'];

        if (strtotime($info['date'])<time()){
            $this->error('原预约时间已过,请重新预约');
        }
        if ($not_allow_cancel_time>0){
            if (time()+$not_allow_cancel_time*60>strtotime($info['date'])){
                $this->error($not_allow_cancel_time.'小时内不允许修改时间');
            }
        }

        Db::startTrans();
        try {
            $info->edit_type = 1;
            $info->is_edit = 1;
            $info->edit_time = time();
            $info->date = $date;
            $info->date_timestamp = strtotime($date);
            $info->save();

            $store = \app\admin\model\Store::get($info['store_id']);
            $project = StoreProject::get($info['project_id']);
            //$message_title = \app\common\model\Config::get(['name'=>'submit_title'])->value;
            $message_title = '预约项目修改成功';
            $request = Request::instance();
            $domain=$request->domain();
            $url = $domain.'/dist/#/complete?order_id='.$order_id;

            $ret = Smslib::send($info->phone, null, 'add',$store['store_name'],$project['project_name'],$info->date,$store['address']);
            if (!$ret) {
                Db::rollback();
                throw new Exception('发送失败，请检查短信配置是否正确');
            }

                $content = '<!DOCTYPE html>
                <html lang="en">
                <head>
                   <meta charset="UTF-8">
                   <meta name="viewport" content="width=device-width, initial-scale=1.0">
                   <title>Appointment Confirmation</title>
                </head>
                <body style="margin: 0; padding: 0;">
                   <table width="100%" cellspacing="0" cellpadding="0">
                      <tr>
                         <td align="center" valign="top" style="padding: 10px;">
                            <table width="100%" max-width="600" cellspacing="0" cellpadding="0">
                               <tr>
                                  <td align="center" style="font-size: 20px; margin-bottom: 30px; padding: 10px 0;">Appointment Scheduled</td>
                               </tr>
                               <tr>
                                  <td style="box-shadow: 0 0 8px 0 #0000001a; padding: 18px 14px; box-sizing: border-box;">
                                     <table width="100%" cellspacing="0" cellpadding="0">
                                        <tr>
                                           <td width="52px" style="color: #7F7F7F; padding-right: 4px;">What</td>
                                           <td>'.$project['project_name'].'</td>
                                        </tr>
                                        <tr>
                                           <td height="16"></td>
                                        </tr>
                                        <tr>
                                           <td width="52px" style="color: #7F7F7F; padding-right: 4px;">When</td>
                                           <td>'.$info['date'].'</td>
                                        </tr>
                                        <tr>
                                           <td height="16"></td>
                                        </tr>
                                        <tr>
                                           <td width="52px" style="color: #7F7F7F; padding-right: 4px;">Where</td>
                                           <td style="word-break: break-word;">'.$store['address'].'</td>
                                        </tr>
                                        <tr>
                                           <td height="20" colspan="2"></td>
                                        </tr>
                                        <tr>
                                           <td colspan="2" align="center" style="color: #A1A1A1; font-size: 14px; text-align: center; padding: 0 5%;">Thank you, your appointment has been successfully scheduled.</td>
                                        </tr>
                                     </table>
                                  </td>
                               </tr>
                   
                               <tr>
                                  <td align="center" valign="middle" style="padding: 30px 0 10px; text-align: center;">
                                     <!--[if mso]>
                                                      <table align="center" border="0" cellspacing="0" cellpadding="0">
                                                      <tr><td>
                                                      <![endif]-->
                                     <a href="'.$url.'"
                                        style="display: block; width: 227px; height: 54px; opacity: 1; background: #030302; color: #fff; line-height: 54px; text-align: center; font-size: 12px; text-decoration: none; margin: 0 auto;">Change/Cancel
                                        Appointment</a>
                                     <!--[if mso]>
                                                      </td></tr>
                                                      </table>
                                                      <![endif]-->
                                  </td>
                               </tr>
                            </table>
                         </td>
                      </tr>
                   </table>
                </body>
                </html>';
            $email = new Email;
            $result = $email
                ->to($info['email'])
                ->subject($message_title)
                ->message($content)
                ->send();

            if (!$result) {
                Db::rollback();
                throw new Exception('邮箱发送失败');
            }
            Db::commit();

        } catch (\Exception $e) {
            Db::rollback();
            $this->error($e->getMessage());
        }
        $this->success('修改成功');
    }

    //取消订单
    public function cancel()
    {
        $order_id = input('order_id',0);
        $info = OrderModel::get($order_id);
        $store = StoreModel::get($info['store_id']);
        $not_allow_cancel_time = $store['not_allow_cancel_time'];

        if ($not_allow_cancel_time>0){
            if (time()+$not_allow_cancel_time*60>strtotime($info['date'])){
                $this->error($not_allow_cancel_time.'小时内不允许取消订单');
            }
        }

        try {
            $order_id = input('order_id',0);
            $order_model = new OrderModel();

            $res = $order_model->cancel($order_id,1);

        }  catch (Exception $e) {
            $this->error($e->getMessage());
        }

        $this->success('取消成功');
    }
}
